﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Web.Security;

using RTGS.Library.Entities.UserManagement;
using RTGS.Library.DataAccess.UserManagement;


using System.Text;
using System.Configuration;


namespace RTGS.Web.form.authentication
{
    

    public partial class login_slide : Page
    {
        RTGS.Web.support.Membership membership = new RTGS.Web.support.Membership(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

        private static int wrongpassword = 0;
        private sysTUserRepo userDal = new sysTUserRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLogRepo logDal = new sysTLogRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLog log = new sysTLog();

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);

        }

        private void InitializeComponent()
        {
            btnLogin.Click += new EventHandler(btnLogin_Click);

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            DoLogin();

        }

        private void DoLogin()
        {
            string username = txtUserID.Text;
            string password = support.Helper.CreatePasswordHash(txtPassword.Text);
            bool isPersistent = chkRemember.Checked;

            sysTUser user;
            string errMsg = string.Empty;

            if (membership.ValidateUser(username, password, out user, out errMsg))
            {
                if (IsAlreadyConnected(username))
                {
                    return; // Exit
                }

                string userData = string.Empty;

                sysTUser obj = userDal.GetById(user.userId);

                    if (obj.islock == false || obj.islock == null)
                    {
                            if (user.userName.Trim().ToLower() != "sa" && user.userName.Trim().ToLower() != "admin")
                            {
                                if (obj.lastLogin != null && obj.lastLogin.ToString() != "")
                                {

                                    long tickDiff = DateTime.Now.Ticks - Convert.ToDateTime(obj.lastLogin).Ticks;
                                    tickDiff = tickDiff / 10000000; //have seconds now
                                    int lastlogin = (int)(tickDiff / 86400);

                           
                                        if (lastlogin >= 30)
                                        {
                                            sysTUser usr = new sysTUser();
                                            usr.userName = user.userName;
                                            usr.modifiedBy = user.userName;
                                            usr.modifiedDate = DateTime.Now;
                                            usr.islock = true;

                                            userDal.UpdateIsLock(usr);

                                            ClientScript.RegisterClientScriptBlock(typeof(Page), "loginwrong", "alert('" + "User anda telah di terkunci,silahkan hubungin Administrator" + "')", true);

                                            return;
                                        }
                                    }
                            }

                        string url = FormsAuthentication.GetRedirectUrl(user.userName, isPersistent);

                        // UserData format -> userid
                        userData = user.userId.ToString();// +"|" + kodeEselon + "|" + deskripsiEselon + "|" + kodeWilayah + "|" + deskripsiWilayah + "|" + kodeSatker + "|" + deskripsiSatker;



                        // Create a new ticket for user that has been authenticated.
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                            user.userName,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(10),
                            isPersistent,
                            userData,
                            FormsAuthentication.FormsCookiePath);

                        // Create the cookie.
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                        cookie.Value = FormsAuthentication.Encrypt(ticket);
                        cookie.Expires = ticket.Expiration;
                        Response.Cookies.Add(cookie);

                        //count wrong password
                        wrongpassword = 0;

                        //update last login date
                        sysTUser usrlast = new sysTUser();
                        usrlast.lastLogin = DateTime.Now;
                        usrlast.userId = user.userId;
                        usrlast.modifiedBy = user.userName;
                        usrlast.modifiedDate = DateTime.Now;
                        userDal.UpdateLastLogin(usrlast);

                        //event log
                        log = new sysTLog();
                        log.logSource = "login-slide.cs";
                        log.logEvent = "Success Login";
                        log.logMessage = string.Empty;
                        log.createdBy = user.userName;
                        log.createdDate = DateTime.Now;

                        logDal.Save(log);

                        // Redirect back to original URL.
                        Response.Redirect(url, false);
                    }
                    else
                    {
                        ClientScript.RegisterClientScriptBlock(typeof(Page), "loginwrong", "alert('" + "User anda telah di terkunci,silahkan hubungin Administrator" + "')", true);
                        return;
                    }
                


            }
            else
            {
                if (string.IsNullOrEmpty(errMsg))
                    errMsg = "- User ID atau Password salah!";

                //ClientScript.RegisterClientScriptBlock(typeof(Page), "loginwrong", "alert('" + errMsg + "')", true);
                wrongpassword++;

                if (username.Trim().ToLower() != "sa" && username.Trim().ToLower() != "admin")
                {
                    if (wrongpassword > 2)
                    {

                        sysTUser obj = new sysTUser();
                        obj.userName = username;
                        obj.modifiedBy = username;
                        obj.modifiedDate = DateTime.Now;
                        obj.islock = true;

                        userDal.UpdateIsLock(obj);

                        errMsg = "User anda telah terkunci,silahkan hubungin Administrator..!";

                        //event log
                        log = new sysTLog();
                        log.logSource = "login-slide.cs";
                        log.logEvent = "Lock User Login";
                        log.logMessage = " Wrong Password and Lock User Login";
                        log.createdBy = username;
                        log.createdDate = DateTime.Now;

                        logDal.Save(log);

                       // ClientScript.RegisterClientScriptBlock(typeof(Page), "loginwrong", "alert('" + "User anda telah di terkunci,silahkan hubungin Administrator" + "')", true);
                    }
                }

                ClientScript.RegisterClientScriptBlock(typeof(Page), "loginwrong", "alert('" + errMsg + "')", true);
            }

        }

        private bool IsAlreadyAccount(string userName)
        {
            bool result = false;

            return result;
        }

        private bool IsAlreadyConnected(string userName)
        {
            List<string> users = Application["UsersLoggedIn"] as List<string>;
            if (users != null)
            {
                lock (users)
                {
                    if (users.Contains(userName))
                    {
                        ClientScript.RegisterClientScriptBlock(typeof(Page), "userExists", "alert('- User ini sudah terlebih dahulu masuk ke aplikasi!')", true);
                        return true;
                    }
                    users.Add(userName);
                }

                Application["UsersLoggedIn"] = users;
            }
            Session["UserLoggedIn"] = userName;
            return false;
        }

    }
}
